import axios from "axios";

const CancelToken = axios.CancelToken;
let cancelStore = null;
let ERRORTOTAL = {}

const instance = axios.create({
    baseURL: 'https://aiclass.xiaosaas.com/',
    timeout: 1000 * 120,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

// 添加请求拦截器
instance.interceptors.request.use( (config) => {
    window.axios_is_request = true
    //取消接口请求
    config.cancelToken = new CancelToken(function executor(cancel){
        cancelStore = cancel
    })
    return config;
},  (error) => {
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use((response) => {
    let url = response.config.url
    if(response.data && response.data.success){
        ERRORTOTAL[url] = 0
        return response.data;
    }
    if(response.config){
        if(!ERRORTOTAL[url]){
            ERRORTOTAL[url] = 0
        }
        ERRORTOTAL[url] += 1;
        response.errorTotal = ERRORTOTAL[url]
    }
    return Promise.reject(response);
},  (error) =>  {
    console.log('error', error)
    if(error.config){
        let url = error.config.url
        if(!ERRORTOTAL[url]){
            ERRORTOTAL[url] = 0
        }
        ERRORTOTAL[url] += 1;
        error.errorTotal = ERRORTOTAL[url]
    }
    if(error.code === 'ERR_NETWORK'){
        window.axios_is_request = false
        return Promise.reject(error.code);
    }
    if (axios.isCancel(error) || error.code === 'ERR_CANCELED') {
        window.axios_is_request = false
        return Promise.reject(error.code);
    }
    return Promise.reject(error);
});
export const cancel = function (){
    if(window.axios_is_request && cancelStore){
        cancelStore()
    }
};
export default instance
